﻿using System;
using System.IO;
using System.Text;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.Text;

namespace Beeflys.Generator.App
{
    class Program
    {
        static void Main(string[] args)
        {
            string str = AppContext.BaseDirectory;
            Console.WriteLine(str);

            string baseDirectory = AppContext.BaseDirectory.Replace(@"\", "/");
            baseDirectory = baseDirectory.Replace("src/Beeflys.Generator.App", "test/actor_test");

            string[] paths =
            {
                Path.Combine(baseDirectory, "eLoop.dll"),
                //Path.Combine(baseDirectory, "Google.Protobuf.dll"),
                Path.Combine(baseDirectory, "Letter.IO.dll"),
                Path.Combine(baseDirectory, "Letter.Tcp.dll"),
                Path.Combine(baseDirectory, "Beeflys.dll"),
            };

            string source = new DirectoryInfo(baseDirectory).Parent.Parent.Parent.FullName;


            CSharpCompilation compilation = CSharpCompilation.Create("test");
            var systemReference = MetadataReference.CreateFromFile(typeof(object).Assembly.Location);
            compilation.AddReferences(systemReference);

            for (int i = 0; i < paths.Length; i++)
            {
                var path = paths[i];
                if (!File.Exists(path))
                {
                    Console.WriteLine("不存在的程序集：" + path);
                }
                else
                {
                    Console.WriteLine("加载的程序集：" + path);
                }

                var reference = MetadataReference.CreateFromFile(path);
                compilation = compilation.AddReferences(reference);
            }

            DirectoryInfo directory = new DirectoryInfo(source);
            var childFileInfos = directory.GetFiles("*.cs", SearchOption.AllDirectories);
            foreach (var fileInfo in childFileInfos)
            {
                if (!fileInfo.Exists) continue;

                var fs = fileInfo.OpenRead();
                var text = SourceText.From(fs, Encoding.UTF8);
                var tree = CSharpSyntaxTree.ParseText(text);
                compilation = compilation.AddSyntaxTrees(tree);

                fs.Dispose();
            }


            Execute(compilation);
        }
        
        private static void Execute(CSharpCompilation compilation)
        {
            USyntaxTrees.Parse(compilation);
            var item = Filter.Start();

            if (item.errors != null)
            {
                foreach (var error in item.errors)
                {
                    Console.WriteLine(error.text);
                }

                return;
            }

            var pros = Generator.Start(item.protocols, item.messengers);
            foreach (var s in pros)
            {
                Console.WriteLine(s.Build());
            }
        }
    }
}